package org.example.dao;

import org.example.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Description
 * @Author 魏锴
 * @Date 2023/12/13
 */
@Component
public class userDao {
    @Autowired
    public JdbcTemplate jdbcTemplate;

    public boolean isExit(String name) {
        String sql = "select count(*) from users where name = ?;";
        return jdbcTemplate.queryForObject(sql, Integer.class, name) > 0;
    }

    public boolean register(UserVO user) {//注册用户
        if (isExit(user.getUsername())) return false;//存在
        String sql = "insert into users(`name`, `password`, age, birthday) values (?, ?, ?, ?) ;";
        return jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getAge(), user.getBirthday()) == 1;
    }

    public boolean login(String name, String password) {//用户登录
        String sql = "select count(*) from users where name = ? and password = ?;";
        return jdbcTemplate.queryForObject(sql, Integer.class, name, password) > 0;
    }

    public UserVO getUser(String name) {//获取用户
        if (!isExit(name)) return null;//用户不存在
        String sql = "select name, password, age, birthday from users where name = ?";
        return jdbcTemplate.queryForObject(sql, this::userVOTransform, name);
    }

    private UserVO userVOTransform(ResultSet rs, int RowNum) throws SQLException {
        return new UserVO(
                rs.getString("name"),
                rs.getString("password"),
                rs.getInt("age"),
                rs.getDate("birthday")
        );
    }
}
